package org.linphone.sub.sublist;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Chronometer;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.gyf.barlibrary.ImmersionBar;
import com.skyfishjy.library.RippleBackground;
import com.topeet.serialtest.serial;

import org.linphone.LinphoneActivity;
import org.linphone.R;
import org.linphone.sub.bean.SubConf;
import org.linphone.sub.treeview.FirstItemViewFactory;
import org.linphone.sub.treeview.FirstNameView;
import org.linphone.sub.utils.Screensaver;
import org.linphone.sub.utils.VolumeUtil;
import org.linphone.utils.SpUtil;

import java.util.ArrayList;
import java.util.List;

import me.texy.treeview.TreeNode;
import me.texy.treeview.TreeView;
import pl.droidsonroids.gif.GifImageView;

/**
 * Created by Xiang on 2018/5/15.
 */

public class SubListActivity extends AppCompatActivity implements IListView,SubConf.IOnDataChange,Screensaver.OnTimeOutListener {

	//Presenter管理者
	private IListPresenter mPresenter;
	//展示的界面的第一级标签名
	private FirstNameView fistNameView;
	//根节点
	private TreeNode rootNode;
	//次节View
	private TreeView treeView;
	//主View
	private LinearLayout myfirstViwe;
	//根节点集合
	private List<TreeNode> mTreeNodes;
	//分站状态码
	public static int STATE_NUM = 0;
	//广播View
	private LinearLayout ll_broadcast;
	//倒计时显示View
	private RippleBackground rpg_broadcast;
	//广播动画接收
	private Chronometer ch_timer;
	//调用摘机挂机
	private serial serial = new serial();
	//当前音量值
	private int currentVolume = 8;
	//private int currentVolume = 6;
	private GifImageView sub_gif_screen;
//	private Screensaver mScreensaver;

	//消息接收者
	@SuppressLint("HandlerLeak")
	private Handler mHandler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what){
				case 1:
					if(myfirstViwe!=null){
						Log.i("123456789", "onChange: 刷刷刷。。。");
						myfirstViwe.removeAllViews();
					}
					break;
			}
		}
	};

	//开启界面
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_sub_list);
		ImmersionBar.with(this).init();
		init();
		// 在最开始的时候构建presenter
		mPresenter = new ListPresenter(this);
		SubConf.getmInstance().bind(this);//注册监听

		//mScreensaver = new Screensaver(5000); //定时5秒
		//mScreensaver.setOnTimeOutListener(this); //监听
		//mScreensaver.start(); //开始计时
	}

	@Override
	protected void onResume() {
		super.onResume();
		AllScreen();
	}

	//初始化基本数据
	private void init() {
		myfirstViwe = (LinearLayout) findViewById(R.id.ll_sublist);
		ll_broadcast = (LinearLayout) findViewById(R.id.ll_broadcast);
		ch_timer = (Chronometer) findViewById(R.id.ch_timer);
		rpg_broadcast = (RippleBackground) findViewById(R.id.rpg_broadcast);
		fistNameView = new FirstNameView();
		sub_gif_screen = (GifImageView) findViewById(R.id.sub_gif_screen);
	}

	//开启配置信息
	@Override
	protected void onStart() {
		super.onStart();
		mPresenter.start(this);
	}

	//销毁界面
	@Override
	protected void onDestroy() {
		SubConf.getmInstance().unbind();
		if (mPresenter != null) {
			mPresenter.destroy(this);
			mPresenter = null;
		}

		//mScreensaver.stop(); //停止计时
		super.onDestroy();
	}

	//全屏展示
	public void AllScreen(){
		View decorView =getWindow().getDecorView();
		int uiOptions = 0;
		if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN) {
			uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_FULLSCREEN;
		}
		decorView.setSystemUiVisibility(uiOptions);

	}

	//更新分站数据信息
	@Override
	public void updateList(SubConf sc) {

		loadData(sc);
		treeView = new TreeView(rootNode,this,new FirstItemViewFactory());

		final View view = treeView.getView();
		view.setLayoutParams(new ViewGroup.LayoutParams(
				ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if(myfirstViwe!=null){

					myfirstViwe.addView(view);
				}
			}
		});
	}

	//获取选中的分站信息
	@Override
	public ArrayList<String> getSelectedSub() {
		return null;
	}

	//加载分站数据信息到界面
	private void loadData(SubConf sc) {
		String str = SpUtil.getString(this,"colliery","阳光三极");
		//跟节点
		rootNode = TreeNode.root();
		TreeNode treeNode1 = new TreeNode(str+"$"+"ABC"+"$"+"ABC"+"$"+"ABC");
		treeNode1.setLevel(0);
		treeNode1.setExpanded(true);
		treeNode1.setItemClickEnable(true);
		if(sc.getSubgrouplist()!=null){
			for(int i = 0; i < sc.getSubgrouplist().size(); i++){
				TreeNode treeNode2 = new TreeNode(sc.getSubgrouplist().get(i).getName()+"$"+"ABC"+"$"+"ABC"+"$"+"ABC");
				treeNode2.setLevel(1);//设置级数
				treeNode2.setExpanded(true);//设置是否展开
				treeNode2.setItemClickEnable(true);//是否可点击

				treeNode1.addChild(treeNode2);
				if(sc.getSubgrouplist().get(i).getSublist()!=null){
					for(int k = 0; k < sc.getSubgrouplist().get(i).getSublist().size(); k++){
						TreeNode treeNode3 = new TreeNode(sc.getSubgrouplist().get(i).getSublist().get(k).getName()
								+ "$"+ sc.getSubgrouplist().get(i).getSublist().get(k).getIp()
								+ "$"+ sc.getSubgrouplist().get(i).getSublist().get(k).getSip()
								+ "$"+ sc.getSubgrouplist().get(i).getSublist().get(k).getStates());

						treeNode3.setLevel(2);
						treeNode3.setItemClickEnable(true);
						treeNode2.addChild(treeNode3);
					}
				}
			}
		}

		rootNode.addChild(treeNode1);

	}

	//数据有更新
	@Override
	public void onChange(SubConf viewModel) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				if(myfirstViwe!=null){
					Log.i("123456789", "onChange: 刷刷刷。。。");
					myfirstViwe.removeAllViews();
				}

			}
		});
		updateList(viewModel);
	}

	@Override
	protected void onPause() {
//		mScreensaver.stop();
		super.onPause();
	}

	@Override
	protected void onRestart() {
	//	mScreensaver.start();
		super.onRestart();
	}

	public void closeAnim(){
		rpg_broadcast.stopRippleAnimation();
		ch_timer.stop();
		ll_broadcast.setVisibility(View.GONE);
	}

	//监听外接按键的输入
	@android.support.annotation.RequiresApi(api = Build.VERSION_CODES.KITKAT)
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {

		if(sub_gif_screen.isClickable()){
//			mScreensaver.resetTime(); //重置时间
			sub_gif_screen.setVisibility(View.GONE);
			sub_gif_screen.setClickable(false);

			return true;
		}else {

			if (event.getKeyCode() == KeyEvent.KEYCODE_F2 && event.getAction() != KeyEvent.ACTION_UP) {
				closeAnim();
				mPresenter.stopBroadcast();

				return true;
			} else if (event.getKeyCode() == KeyEvent.KEYCODE_F1 && event.getAction() != KeyEvent.ACTION_UP) {
				//得到选择的类目
				mTreeNodes = treeView.getSelectedNodes();
				Log.d("wls", "btnClick: " + "************" + mTreeNodes.size());
				final ArrayList<String> alIp = new ArrayList<>();
				final ArrayList<String> alState = new ArrayList<>();
				for (int i = 0; i < mTreeNodes.size(); i++) {
					String[] all = mTreeNodes.get(i).getValue().toString().split("[$]");
					Log.i("123456", "dispatchKeyEvent: " + all.length);
					if (!all[1].equals("ABC")) {
						//Log.d("wls", "init: "  + all[1]);
						alIp.add(all[1]);
						alState.add(all[3]);
					}
				}
				if (STATE_NUM > 0 && STATE_NUM < 4) {
					rpg_broadcast.startRippleAnimation();
					ll_broadcast.setVisibility(View.VISIBLE);
					ch_timer.setBase(SystemClock.elapsedRealtime());//计时器清零
					int hour = (int) ((SystemClock.elapsedRealtime() - ch_timer.getBase()) / 1000 / 60);
					ch_timer.setFormat("0" + String.valueOf(hour) + ":%s");
					ch_timer.start();
					new Thread() {
						@Override
						public void run() {
							//Log.i("wls", "r un: "+al.toString());
							mPresenter.startBroadcast(alIp, alState);
						}
					}.start();
				}
				return true;

			}else if(event.getKeyCode() == KeyEvent.KEYCODE_F3 && event.getAction() != KeyEvent.ACTION_UP){
				//开启sip电话界面
				mTreeNodes = treeView.getSelectedNodes();
				if(mTreeNodes.size()==0){
					//不选分站打开sip电话界面
					if(SubListActivity.STATE_NUM < 4){
						Intent intent = new Intent(this, LinphoneActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("sipnumber","7777");
						startActivity(intent,bundle);
					}

				}else if(mTreeNodes.size()==1){
					//选择分站打开sip电话界面
					if(SubListActivity.STATE_NUM < 4){
						String[] all = mTreeNodes.get(0).getValue().toString().split("[$]");
						SpUtil.putString(this,"sipnumber",all[2]);
						Intent intent = new Intent(this, LinphoneActivity.class);
						Bundle bundle = new Bundle();
						bundle.putString("sipnumber","6666");
						startActivity(intent,bundle);
					}
				}else if(mTreeNodes.size()>1){
					Toast.makeText(this,"请最多选择1个分站...",Toast.LENGTH_SHORT).show();
				}

				return true;
			}else if(event.getKeyCode() == KeyEvent.KEYCODE_F4 && event.getAction() != KeyEvent.ACTION_UP){
				//开启动画
				rpg_broadcast.startRippleAnimation();
				ll_broadcast.setVisibility(View.VISIBLE);
				ch_timer.setBase(SystemClock.elapsedRealtime());//计时器清零
				int hour = (int) ((SystemClock.elapsedRealtime() - ch_timer.getBase()) / 1000 / 60);
				ch_timer.setFormat("0"+String.valueOf(hour)+":%s");
				ch_timer.start();
				return true;
			}else if(event.getKeyCode() == KeyEvent.KEYCODE_F5 && event.getAction() != KeyEvent.ACTION_UP){
				//关闭动画
				closeAnim();
				return true;
			} else if(event.getKeyCode() == KeyEvent.KEYCODE_A && event.getAction() != KeyEvent.ACTION_UP){
				//摘机
				currentVolume = VolumeUtil.getVolume();
				android.util.Log.i("23", "dispatchKeyEvent: "+currentVolume);
				VolumeUtil.setStreamVolume(15);
				serial.Setaudiolocal(0);
				serial.Setaudioremote(0);
				serial.Setaudiophone(1);
				return true;
			}else if(event.getKeyCode() == KeyEvent.KEYCODE_B && event.getAction() != KeyEvent.ACTION_UP){
				//挂机
				VolumeUtil.setStreamVolume(currentVolume);
				serial.Setaudiophone(0);
				serial.Setaudiolocal(1);
				serial.Setaudioremote(1);
				finish();
				return true;
			}

		}

		//else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
		//	return true;
		//}
		return super.dispatchKeyEvent(event);
	}

	@Override
	public void onBackPressed() {
		Intent intent = new Intent();
		intent.setClassName("com.sxygsj.submain", "com.sxygsj.submain.MainActivity");
		startActivity(intent);

//		if (mPresenter != null) {
//			mPresenter.deleteFile(this);
//		}
	}

	@Override
	public void onTimeOut(Screensaver screensaver) {
		Log.d("MainActivity", "时间到了");
		sub_gif_screen.setVisibility(View.VISIBLE);
		sub_gif_screen.setClickable(true);
	}
}
